import {ACLService} from "./acl.service";
import {Directive, Input, TemplateRef, ViewContainerRef} from "@angular/core";

/**
 * Add the template content to the DOM unless the condition is true.
 */
@Directive({selector: '[acl]'})
export class AclDirective {
  private hasView = false;

  constructor(private templateRef: TemplateRef<any>,
              private viewContainer: ViewContainerRef,
              public aclService: ACLService) {
    Array.prototype['in_array'] = function (e) {
      var r = new RegExp(',' + e + ',');
      return (r.test(',' + this.join(this.S) + ','));
    };
  }

  @Input()
  set acl(roles: any) {
    /**
     * 传入角色数组
     * number类型定义为权限点
     * string类型定义为角色
     */
    let condition = false;    //默认无显示权限
    let data = this.aclService.data;
    //传入数据类型必须为数组
    if (this.isArray(roles)) {
      for (let role of roles) {
        if (typeof(role) === 'string') {
          if (data.roles['in_array'](role)) {
            condition = true;
            break;
          }
        }
        else if (typeof(role) === 'number') {
          if (data.abilities['in_array'](role)) {
            condition = true;
            break;
          }
        }
        else {
          alert('请传入string或number类型');
          break;
        }
      }
    }
    else {
      alert('权限调用失败，必须传入数组，number类型为权限点，string类型为角色，可混合传入，例[acl]="[1,2,\'S\']"');
    }
    if (condition && !this.hasView) {
      this.viewContainer.createEmbeddedView(this.templateRef);
      this.hasView = true;
    } else if (!condition && this.hasView) {
      this.viewContainer.clear();
      this.hasView = false;
    }
  }

  isArray(o) {
    return Object.prototype.toString.call(o) == '[object Array]';
  }
}
